// 配置管理
import appConfigJson from '../config/app-config.json';
import { RootConfig, AppConfig, MCPServerConfig, BraveSearchConfig } from '../config/types';

export { AppConfig, MCPServerConfig, BraveSearchConfig } from '../config/types';

export const defaultConfig: AppConfig = {
  enableTools: true,
  maxTokens: 8000,
  temperature: 0.3,
  streamOutput: true,
  showThinking: true,
  autoSave: false,
  saveInterval: 5
};

class ConfigManager {
  private config: RootConfig;

  constructor() {
    this.config = appConfigJson as RootConfig;
  }

  // 获取应用配置
  getAppConfig(): AppConfig {
    return this.config.app || defaultConfig;
  }

  // 获取 MCP 服务器配置列表
  getMCPServers(): MCPServerConfig[] {
    return this.config.mcp?.servers || [];
  }

  // 获取启用的 MCP 服务器
  getEnabledMCPServers(): MCPServerConfig[] {
    return this.getMCPServers().filter(server => server.enabled);
  }

  // 获取 Brave Search API Key
  getBraveSearchApiKey(): string {
    return this.config.braveSearch?.apiKey || '';
  }

  // 获取特定 MCP 服务器配置
  getMCPServer(name: string): MCPServerConfig | undefined {
    return this.getMCPServers().find(server => server.name === name);
  }

  // 应用配置的getter/setter方法（保持向后兼容）
  get<K extends keyof AppConfig>(key: K): AppConfig[K] {
    return this.getAppConfig()[key];
  }

  set<K extends keyof AppConfig>(key: K, value: AppConfig[K]) {
    this.config.app[key] = value;
    this.saveConfig();
  }

  getAll(): AppConfig {
    return { ...this.getAppConfig() };
  }

  private saveConfig() {
    try {
      // 这里可以保存配置到文件
      const fs = require('fs');
      const configPath = require('path').join(__dirname, 'config', 'app-config.json');
      fs.writeFileSync(configPath, JSON.stringify(this.config, null, 2));
    } catch (error) {
      console.warn('保存配置失败:', error);
    }
  }

  reset() {
    this.config.app = { ...defaultConfig };
    this.saveConfig();
  }

  showConfig(): string {
    let result = '\n=== 当前配置 ===\n';
    
    result += '应用配置:\n';
    Object.entries(this.getAppConfig()).forEach(([key, value]) => {
      result += `  ${key}: ${value}\n`;
    });

    result += '\nMCP 服务器:\n';
    this.getMCPServers().forEach(server => {
      result += `  - ${server.name}: ${server.enabled ? '启用' : '禁用'}\n`;
      result += `    命令: ${server.command}\n`;
      if (server.cwd) result += `    工作目录: ${server.cwd}\n`;
      if (server.description) result += `    描述: ${server.description}\n`;
    });

    result += `\nBrave Search API: ${this.getBraveSearchApiKey() ? '已配置' : '未配置'}\n`;
    
    return result;
  }

  // 新增：获取完整配置
  getFullConfig(): RootConfig {
    return this.config;
  }
}

export const configManager = new ConfigManager();
